#!/bin/bash
DB_DUMP_FILE=dbdump.sql
PASSWORD=gm8JU42k8g
LOCAL_MYSQL_COMMAND=/cygdrive/c/wamp/bin/mysql/mysql5.1.53/bin/mysql
DB_NAME=heyidleb_db1
JAR_DIR=/cygdrive/c/wamp/www/bookshelf/scripts/IndexCreator/deployed
INDEX_DIR=c:\\indexes\\
TIMESTAMP=`date +%s`

#echo "Dump live database"
#echo Login to www.heyidlebooks.com $PASSWORD
#ssh heyidleb@www.heyidlebooks.com "mysqldump --database heyidleb_db1 -u heyidleb -p$PASSWORD > ~/$DB_DUMP_FILE" || exit 1

#TMP=`mktemp -d`
#cd $TMP
#echo Copy $DB_DUMP_FILE from live to $TMP
#scp heyidleb@www.heyidlebooks.com:~/$DB_DUMP_FILE ./ || exit 2

TMP_DIR=/tmp/tmp.LjT8i46W7x
TMP_FILE=$TMP_DIR/$DB_DUMP_FILE
echo Recreate local database $DB_NAME
$LOCAL_MYSQL_COMMAND -u root -p -e "DROP DATABASE IF EXISTS $DB_NAME;CREATE SCHEMA $DB_NAME DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;" || exit 3
$LOCAL_MYSQL_COMMAND -u root -p --database $DB_NAME < $TMP_FILE || exit 4
echo Generate index for local database $DB_NAME to $INDEX_DIR
cd $JAR_DIR
echo java -jar IndexCreator-0.0.1-SNAPSHOT.jar $INDEX_DIR
java -jar IndexCreator-0.0.1-SNAPSHOT.jar $INDEX_DIR || exit 5

echo Backup live index
echo Login to www.heyidlebooks.com $PASSWORD
ssh heyidleb@www.heyidlebooks.com "mv /home/heyidleb/indexes/book/ /home/heyidleb/indexes/book_$TIMESTAMP" || exit 6
ssh heyidleb@www.heyidlebooks.com "mkdir /home/heyidleb/indexes/book/" || exit 7
scp /cygdrive/c/indexes/* heyidleb@www.heyidlebooks.com:~/indexes/book/ || exit 8
ssh heyidleb@www.heyidlebooks.com "chmod 644 /home/heyidleb/indexes/book/*" || exit 9

echo cleanup...
ssh heyidleb@www.heyidlebooks.com "rm /home/heyidleb/$DB_DUMP_FILE"
exit 0